package com.jk.garden1.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jk.garden1.dao.*;
import com.jk.garden1.entity.FollowPeopleEntity;
import com.jk.garden1.entity.SubscribeEntity;
import com.jk.garden1.entity.VisitantEntity;
import com.jk.garden1.entity.VisitorEntity;
import org.apache.commons.io.FileUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 访客管理
 */
@Service
public class VisitorService {
    @Autowired
    private VisitorDao visitorDao;
    @Autowired
    private VisitorDaos visitorDaos;
    @Autowired
    private ElasticsearchRestTemplate es;
    @Autowired
    private EsVisitorDao esVisitorDao;
    @Autowired
    private FollowPeopleDao followPeopleDao;
    @Autowired
    private SubscribeDao subscribeDao;

    /**
     * 查询全部
     */
    public List<VisitorEntity> selectVisitorList() {

        return visitorDao.selectList(null);
    }
    /**
     * 新增预约
     */
    public void addVisitor(VisitorEntity visitorEntity) {
        visitorDao.insert(visitorEntity);
    }

    /**
     * 拉黑
     * @param visitorid
     */
    public void updateState(Integer visitorid) {
        visitorDaos.updateState(visitorid);
    }


    /**
     * 新增索引
     */
    public void create(){
        es.createIndex(VisitorEntity.class);
        QueryWrapper wp=new QueryWrapper();
        List<VisitorEntity> list = visitorDao.selectList(wp);
        list.forEach(a -> {
            esVisitorDao.save(a);
        });
    }


    /**
     * es高亮查询
     * @param visitor
     * @return
     */
    public Object queryEsList(VisitorEntity visitor) {
        if (es.indexExists(VisitorEntity.class)){
            create();
        }
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //电话精确查
        if(StringUtils.hasText(visitor.getVisitorphone())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.termQuery("visitorphone",visitor.getVisitorphone()));
        }
        //姓名模糊查
        if(StringUtils.hasText(visitor.getVisitorname())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("visitorname",visitor.getVisitorname()))
                    .withHighlightFields(new HighlightBuilder.Field("visitorname").preTags("<font color='red'>").postTags("</font>"));
        }
        SearchQuery build = nativeSearchQueryBuilder.build();
        if(StringUtils.hasText(visitor.getVisitorname())){
            AggregatedPage<VisitorEntity> employeeEntity = es.queryForPage(build, VisitorEntity.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    SearchHits hits = searchResponse.getHits();
                    List list = new ArrayList();
                    for (SearchHit hit : hits) {
                        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                        sourceAsMap.put("visitorname", highlightFields.get("visitorname").getFragments()[0].toString());
                        list.add(sourceAsMap);
                    }
                    return new AggregatedPageImpl<>(list);
                }
                @Override
                public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
                    return null;
                }
            });
            return employeeEntity.getContent();
        }else{
            List<VisitorEntity> list2 = es.queryForList(build, VisitorEntity.class);
            return  list2;
        }
    }

    public List<VisitorEntity> findfangkeCount() {
        return visitorDaos.findfangkeCount();
    }


    public SubscribeEntity findsuifangCount(Integer visitorid) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("subscribeid",visitorid);
        SubscribeEntity subscribeEntity = subscribeDao.selectOne(wrapper);
        System.out.println(subscribeEntity);
        return subscribeEntity;

//        FollowPeopleEntity followPeopleEntity = followPeopleDao.selectById(visitorid);
//        System.out.println("followPeopleEntity = " + followPeopleEntity);

    }
}
